package com.zhengqiangblog.canary.account.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;

import com.zhengqiangblog.canary.account.model.Account;

public class AccountDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	private AccountRowMapper accountRowMapper = new AccountRowMapper();

	public Account getAccountById(long id) {
		String sql = "select * from account where id = ?";
		return jdbcTemplate.queryForObject(sql, accountRowMapper, id);
	}

	public long saveAccount(Account account) {
		String sql = "insert into account (id, phone, email, gender, reg_date, status) values (?, ?, ?, ?, ?, ?)";
		return jdbcTemplate.update(sql, new PreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setLong(1, account.getId());
				ps.setString(2, account.getPhone());
				ps.setString(3, account.getEmail());
				ps.setInt(4, account.getGender());
				ps.setTimestamp(5, new Timestamp(account.getRegDate().getTime()));
				ps.setInt(6, account.getStatus());
			}
		});
	}

	private class AccountRowMapper implements RowMapper<Account> {
		@Override
		public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
			Account account = new Account();
			account.setId(rs.getLong("id"));
			account.setPhone(rs.getString("phone"));
			account.setEmail(rs.getString("email"));
			account.setGender(rs.getInt("gender"));
			account.setRegDate(rs.getTimestamp("reg_date"));
			account.setStatus(rs.getInt("status"));
			return account;
		}
	}
}
